package com.example.cloud.controller;

import com.example.cloud.entities.PayDTO;
import com.example.cloud.resp.ResultData;
import jakarta.annotation.Resource;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: Yun
 * @Date: 2024/3/18
 */
@RestController
@RequestMapping("/consumer/pay")
public class OrderController {
    // 写死,硬编码
    //public static final String PaymentSrv_URL = "http://localhost:8001";
    public static final String PaymentSrv_URL = "http://cloud-payment-service";//服务注册中心上的微服务名称


    @Resource
    private RestTemplate restTemplate;

    @GetMapping("/insert")
    public ResultData insertOrder(@RequestBody PayDTO payDTO) {
        return restTemplate.postForObject(PaymentSrv_URL + "/pay/insert", payDTO, ResultData.class);
    }


    @GetMapping("/select/{id}")
    public ResultData selectPayInfoById(@PathVariable("id") Integer id) {
        return restTemplate.getForObject(PaymentSrv_URL + "/pay/select/" + id, ResultData.class, id);
    }


    @GetMapping("/update")
    public void updateOrder(@RequestBody PayDTO payDTO) {
        restTemplate.put(PaymentSrv_URL + "/pay/update", payDTO);
    }

    @GetMapping("/delete/{id}")
    public void deleteOrder(@PathVariable("id") Integer id) {
        String url = PaymentSrv_URL + "/pay/delete/" + id;
        Map map = new HashMap();
        map.put("id", id);
        restTemplate.delete(PaymentSrv_URL + "/pay/delete/" + id, map);
    }

    @GetMapping("/selectAll")
    public ResultData selectAllOrder() {
        return restTemplate.getForObject(PaymentSrv_URL + "/pay/selectAll", ResultData.class);
    }


    @GetMapping("/getInfo")
    public String getInfoByConsul() {
        return restTemplate.getForObject(PaymentSrv_URL + "/pay/getInfo", String.class);
    }

    @Resource
    private DiscoveryClient discoveryClient;

    @GetMapping("/discovery")
    public String discovery() {
        List<String> services = discoveryClient.getServices();
        for (String element : services) System.out.println(element);

        System.out.println("===================================");

        List<ServiceInstance> instances = discoveryClient.getInstances("cloud-payment-service");
        for (ServiceInstance element : instances)
            System.out.println(element.getServiceId() + "\t" + element.getHost() + "\t" + element.getPort() + "\t" + element.getUri());

        return instances.get(0).getServiceId() + ":" + instances.get(0).getPort();
    }
}
